package cn.liuyi.weiyi;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.edu.pku.tools.SharedPreferencesHelper;
import cn.edu.pku.tools.YJRHttpClient;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;

public class StartChatActivity extends SherlockActivity implements OnClickListener{

	LayoutInflater inflater;
	ActionBar actionBar;
	View title_bar;
	Context context;
	String response;
	JSONObject jsonInfo, doctor;
	SharedPreferencesHelper spHelper;
	String consultPrice, responseTime;
	TextView price_tv,reply_tv;
	Button start_btn;
	String doc_id;
	String age;
	String des;
	String sym;
	RelativeLayout gender_rl, age_rl, sym_rl;
	TextView gender_tv, age_tv, sym_tv, des_tv;
	String gender = "男", gender_type= "M";
	String[] genders = new String[] {"男","女","未知"};
	String[] gender_types = new String[]{"M","F","U"};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_start_chat);
		inflater = this.getLayoutInflater();
		actionBar = getSupportActionBar();
		context = this;
		this.spHelper = new SharedPreferencesHelper(this.context);
		Intent intent = this.getIntent();
		String tmp = intent.getStringExtra("doctor");
		try {
			doctor = new JSONObject(tmp);
			doc_id = doctor.getString("id");
			consultPrice = doctor.getString("consultPrice");
			responseTime = doctor.getString("maxResponseGap");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		initTitleBar();
		
		initComponent();
		
		initEventListener();
		
		
		
	
	}
	
	private void initTitleBar(){
		ActionBar.LayoutParams lp = new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,ActionBar.LayoutParams.WRAP_CONTENT,Gravity.CENTER);
		title_bar = inflater.inflate(R.layout.start_chat_action_bar, null);
		
		actionBar.setCustomView(title_bar,lp);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayShowTitleEnabled(false);
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionBar.setDisplayShowCustomEnabled(true);
	}
	private void initComponent(){
		start_btn = (Button) findViewById(R.id.start_btn);
		reply_tv = (TextView) findViewById(R.id.reply_tv);
		price_tv = (TextView) findViewById(R.id.price_tv);
		price_tv.setText(consultPrice + " 元/次");
		reply_tv.setText(responseTime + " 小时");
		
		gender_rl = (RelativeLayout) findViewById(R.id.gender_rl);
		age_rl = (RelativeLayout) findViewById(R.id.age_rl);
		sym_rl = (RelativeLayout) findViewById(R.id.sym_rl);
		
		gender_tv = (TextView) findViewById(R.id.gender_tv);
		age_tv = (TextView) findViewById(R.id.age_tv);
		sym_tv = (TextView) findViewById(R.id.sym_tv);
		des_tv = (TextView) findViewById(R.id.des_tv);
		
		
	}
	
	private void initEventListener(){
		
		start_btn.setOnClickListener(this);
		gender_rl.setOnClickListener(this);
		age_rl.setOnClickListener(this);
		sym_rl.setOnClickListener(this);
		des_tv.setOnClickListener(this);
		
	}

	@SuppressLint("NewApi")
	@Override
	public void onClick(View v) {
		Intent intent;
		switch(v.getId()){
		
		case R.id.start_btn:
			startChat("1");
//			intent = new Intent(StartChatActivity.this, ChatActivity.class);
//			startActivity(intent);
			break;
		case R.id.gender_rl:
			showGenderPicker();
			break;
		case R.id.age_rl:
			intent = new Intent(StartChatActivity.this, SetAgeActivity.class);
			startActivityForResult(intent,0);
			break;
		case R.id.sym_rl:
			
			break;
		case R.id.des_tv:
			intent = new Intent(StartChatActivity.this, AddDesActivity.class);
			startActivityForResult(intent,1);
			break;
		default:
				break;
		}
		
	}
	
	private void startChat( String order_id){
		order_id = "1";
		RequestParams params = new RequestParams(); 
		params.add("consult.doctor.id", doc_id);
		params.add("consult.order.id", order_id);
		params.add("consult.gender", gender_type);
		params.add("consult.age", age);
		params.add("consult.symptomIds", sym);
		params.add("consult.description", des);
		YJRHttpClient.post(context,"/patient/addConsult", params, new JsonHttpResponseHandler(){
			 @Override  
	            public void onSuccess(JSONObject data) {  
	             	jsonInfo = data;
	             	//Toast.makeText(context, data.toString(), Toast.LENGTH_SHORT).show();
	             	try {
						if(jsonInfo.getInt("result") == 1){
							YJRHttpClient.setCookie(context); 
							Toast.makeText(context, "发起咨询成功,开始支付", Toast.LENGTH_SHORT).show();
							String order_id = jsonInfo.getJSONObject("response").getJSONObject("order").getString("id");
							pay(order_id);
							Log.v("liuyi", data.toString());
							//TODO
						}else{
							Toast.makeText(context, jsonInfo.getString("info"), Toast.LENGTH_SHORT).show();
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }  
		});
	}
	
	
	private void pay( String order_id){
		RequestParams params = new RequestParams(); 
		params.add("orderId", order_id);
		YJRHttpClient.post(context,"/patient/finishOrder", params, new JsonHttpResponseHandler(){
			 @Override  
	            public void onSuccess(JSONObject data) {  
	             	jsonInfo = data;
	             	//Toast.makeText(context, data.toString(), Toast.LENGTH_SHORT).show();
	             	try {
						if(jsonInfo.getInt("result") == 1){
							YJRHttpClient.setCookie(context); 
							Toast.makeText(context, "支付成功", Toast.LENGTH_SHORT).show();
							Intent intent = new Intent(StartChatActivity.this, ChatActivity.class);
							intent.putExtra("doctor", doctor.toString());
							intent.putExtra("consultStatus", "A");
							startActivity(intent);
							//TODO
						}else{
							Toast.makeText(context, jsonInfo.getString("info"), Toast.LENGTH_SHORT).show();
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }  
		});
	}
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
	      switch (requestCode) {
	      case 0:
	    	  if(data!=null){
	    		  age = data.getStringExtra("age");
	    		  age_tv.setText(age);
	    	  }
	    	  break;
	      case 1:
	    	  if(data!=null){
	    		  des = data.getStringExtra("des");
	    		  des_tv.setText(des);
	    	  }
	    	  break;
	      default:  
	          break;  

	      }  
	      super.onActivityResult(requestCode, resultCode, data);  
	  }  
	private void showGenderPicker() {
		Builder builder=new AlertDialog.Builder(context);
	    builder.setTitle("选择性别");
	    builder.setSingleChoiceItems(genders, 0,new DialogInterface.OnClickListener(){

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				gender = genders[which];
				gender_type = gender_types[which];
			}
	    	
	    });
	    builder.setPositiveButton("确定", new DialogInterface.OnClickListener(){

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				gender_tv.setText(gender);
				dialog.dismiss();
			}
	    	
	    });
	    builder.setNegativeButton("取消", null);
	    AlertDialog dialog=builder.create();
	    dialog.show();
	}

}